# 导入必要的模块
import tornado.ioloop
import tornado.web
import tornado.websocket

# 定义WebSocket处理类
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print("WebSocket opened")

    def on_message(self, message):
        print("Received message: " + message)
        # Echo the message back to the client
        self.write_message(u"服务器回复: " + message)

    def on_close(self):
        print("WebSocket closed")

    def check_origin(self, origin):
        # 允许跨域请求
        return True

# 创建Tornado应用
def make_app():
    return tornado.web.Application([
        (r"/api/websocket", WebSocketHandler),
    ])

# 主函数
if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    print("WebSocket服务器启动，监听端口：8888")
    tornado.ioloop.IOLoop.current().start()
